﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using SystemSettings;
using Labthink.PCSoft.UniversalHost4.DataAccess;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using NLog;

namespace Labthink.PCSoft.UniversalHost4
{
    public partial class App
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();

        private void App_Startup(object sender, StartupEventArgs se)
        {
            try
            {
                string path = this.GetType().Assembly.Location;
                string ico = Path.GetDirectoryName(path) + @"/Labthink-C.ico";
                var exeName = Path.GetFileNameWithoutExtension(path);
                Mutex _mutex = new Mutex(true, exeName, out bool ret);

                if (!ret)
                    Environment.Exit(0);

                _logger.Debug("Startup");
                Recover();
                Common.UserSettings = UserSettings.Load();
                SystemInfo.LocaleInConfig = Common.UserSettings.Locale;

                LanguageManager.Initialize();
                LanguageManager.CurrentLanguage = SystemInfo.GetCurrentLocale();

                AppDomain.CurrentDomain.UnhandledException += (s, e) =>
                    LogUnhandledException((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");

                DispatcherUnhandledException += (s, e) =>
                    LogUnhandledException(e.Exception, "Application.Current.DispatcherUnhandledException");

                TaskScheduler.UnobservedTaskException += (s, e) =>
                    LogUnhandledException(e.Exception, "TaskScheduler.UnobservedTaskException");

                var vi = new StringBuilder();
                vi.Append($"Operation System: {SystemInfo.OsName}(");

                if (!string.IsNullOrEmpty(SystemInfo.ReleaseId))
                {
                    vi.Append($"{SystemInfo.ReleaseId}, ");
                }

                vi.Append($"{SystemInfo.Version}, {SystemInfo.Architecture})");
                _logger.Info(vi.ToString());
                _logger.Info($"Processor: {SystemInfo.Processor}");
                _logger.Info($"System locale: {SystemInfo.Locale}");
                _logger.Info($"Resolution: {SystemInfo.Resolution}");

                // 在启动界面进行初始化
                Common.BaseInfo = ConfigAndSettings.GetBaseInfo();
                Common.GmpInfo = ConfigAndSettings.GetGmpInfo();
                Common.SafeInfo = ConfigAndSettings.GetSafeInfo();
                Common.ComInfo = ConfigAndSettings.GetComInfo();
                Common.UiSetting = ConfigAndSettings.GetUiSetting();
                Common.TestConfig = ConfigAndSettings.GetTestConfig();
                DataManage.Init();
                Common.TestStatus = TestStatus.Idle;
                string cu = Path.Combine(Common.LocalPath, "Config", CurrentRepository.Unit);
                if (Directory.Exists(cu))
                {
                    Common.LoadDefaultParams(CurrentRepository.Unit);
                }

                // 加载标定信息
                //Common.LoadCalis();
                //Common.LoadSensorCalis();
                if (!DebugHelper.IsInDebugMode())
                {
                    //创建快捷方式和自启动
                    string name = System.Configuration.ConfigurationManager.AppSettings["ShortcutName"];
                    string desc = Common.BaseInfo.Name;
                    //try
                    //{
                    //    if (!Debugger.IsAttached) ShortcutAndAutoRunCreator.SetAutoRun(path, name);
                    //}
                    //catch (Exception e)
                    //{
                    //    _logger.Error("设置自启动出错");
                    //}

                    //try
                    //{
                    //    if (!ShortcutAndAutoRunCreator.ExistsShortcutOnDesktop(name))
                    //    {
                    //        if (!Debugger.IsAttached) ShortcutAndAutoRunCreator.CreateShortcutOnDesktop(name, path, desc, ico);
                    //    }
                    //}
                    //catch (Exception e)
                    //{
                    //    _logger.Error("设置桌面快捷方式出错");
                    //}
                }
                var window = States.Instance.MainWindow;
                Current.MainWindow = window;
                window.Show();
            }
            catch (Exception ex)
            {
                _logger.Error("软件运行出错");
                _logger.Error(ex);
            }
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            //LogTo.Debug("Activated");
        }

        protected override void OnDeactivated(EventArgs e)
        {
            base.OnDeactivated(e);
            //LogTo.Debug("Deactivated");
        }

        protected override void OnExit(ExitEventArgs e)
        {
            try
            {
                _logger.Debug("Exit");
            }
            finally
            {
                base.OnExit(e);
            }
        }

        protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
        {
            // 试验中，试验未保存等
            string msg = $"{e.ReasonSessionEnding}. End session?";
            //MessageBoxResult result = MessageBox.Show(msg, "Session Ending", MessageBoxButton.YesNo);
            var result = MyMessageBox.Show(Application.Current.MainWindow, msg, MyMessageBoxButton.YesNo, MyMessageBoxImage.Warning);
            if (result != MyMessageBoxResult.Yes)
            {
                e.Cancel = true;
            }
            else
            {
                _logger.Debug($"SessionEnding: {e.ReasonSessionEnding}");
            }
        }

        private void LogUnhandledException(Exception ex, string msg)
        {
            _logger.Error(msg);
            _logger.Error("软件运行出错" + ex.Message);
            _logger.Error(ex.StackTrace);
        }

        private void CheckAdministrator()
        {
            var wi = WindowsIdentity.GetCurrent();
            var wp = new WindowsPrincipal(wi);

            bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);

            if (!runAsAdmin)
            {
                var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);

                processInfo.UseShellExecute = true;
                processInfo.Verb = "runas";

                try
                {
                    Process.Start(processInfo);
                }
                catch (Exception ex)
                {
                    _logger.Error("软件运行出错");
                    _logger.Error(ex);
                }

                Environment.Exit(0);
            }
        }

        private void Recover()
        {
            //判断是否存在初始化标识
            var iniFile = Path.Combine(Common.LocalPath, "init");
            if (!File.Exists(iniFile))
            {
                _logger.Debug("无初始化标识，跳过初始化");
                return;
            }

            //恢复默认数据和配置
            DataManage.Recover();

            //恢复默认流程
            //ConfigAndSettings.Recover();

            //删除初始化标识
            File.Delete(iniFile);
        }
    }
}
